package io.web.api.aop;

import io.web.api.annotation.RPC;
import io.web.utils.BusinessException;
import io.web.utils.ErrorCode;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;

/**
 * 权限校验 AOP
 *
 */
@Aspect
@Component
public class RPCInterceptor {

    /**
     * 执行拦截,判断是否为内部feign调用
     *
     * @param joinPoint
     * @param rpc
     * @return
     */
    @Around("@annotation(rpc)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, RPC rpc) throws Throwable {
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();

        String authorization = request.getHeader("Authorization");
        if (StringUtils.isBlank(authorization)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        String auth = "Basic " + new String(Base64.getEncoder().encode("api-backend:api-backend".getBytes(StandardCharsets.UTF_8)));
        if (!authorization.equals(auth)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 通过权限校验，放行
        return joinPoint.proceed();
    }
}

